//
//  MainViewController.swift
//  Trill
//
//  Created by 顾钱想 on 2019/11/9.
//  Copyright © 2019 顾钱想. All rights reserved.
//

import UIKit
import ZFPlayer
class MainViewController: UIViewController {
    let identifier = "SmallVideoCell"
    lazy var tableView: UITableView = {
        let _tableview = UITableView(frame: CGRect.init(x: 0, y: 0, width: Configs.Dimensions.screenWidth, height: Configs.Dimensions.screenHeight))
        //有翻页效果
        _tableview.isPagingEnabled = true
        _tableview.showsVerticalScrollIndicator = false
        _tableview.register(UINib.init(nibName: "SmallVideoCell", bundle: nil), forCellReuseIdentifier: identifier)
        _tableview.delegate = self
        _tableview.dataSource = self
        return _tableview
    }()

     private lazy var controlView = ZFPlayerControlView()


    // MARK: - Lazyload
      private lazy var playerManager: ZFAVPlayerManager = {
          let playerManager = ZFAVPlayerManager()
          playerManager.scalingMode = .aspectFill
          return playerManager
      }()
    fileprivate var player: ZFPlayerController = ZFPlayerController.init()
    override func viewDidLoad() {
        super .viewDidLoad()
        self.view.addSubview(tableView)
        guard let url = URL(string: "http://tb-video.bdstatic.com/tieba-smallvideo-transcode/3612804_e50cb68f52adb3c4c3f6135c0edcc7b0_3.mp4") else { return }

        /// player的tag值必须在cell里设置
        player = ZFPlayerController.init(scrollView: tableView, playerManager: playerManager, containerViewTag: 100)
        self.player.controlView = controlView
        self.player.assetURLs = [url,url,url,url,url];
        /// 0.8是消失80%时候，默认0.5
        self.player.playerDisapperaPercent = 0.8;
        self.player.playerApperaPercent = 0.0
        self.player.stopWhileNotVisible = false


        // 滑动时自动播放视频
        tableView.zf_scrollViewDidStopScrollCallback = { [weak self] indexPath in
           if (!((self?.player.playingIndexPath) != nil)) {
               self?.playTheVideoAtIndexPath(indexPath: indexPath, scrollToTop: false)
           }
        }


        // 播放结束时重新播放
        player.playerDidToEnd = { [weak self] _ in
           self?.player.currentPlayerManager.replay?()
        }
    }

    override func viewDidAppear(_ animated: Bool) {
        super .viewDidAppear(animated)
        self.tableView.zf_filterShouldPlayCellWhileScrolled { indexPath in
            self.playTheVideoAtIndexPath(indexPath: indexPath, scrollToTop: false)

        }

    }



    func playTheVideoAtIndexPath(indexPath: IndexPath) {
        /// 如果正在播放的index和当前点击的index不同，则停止当前播放的index
        if player.playingIndexPath != indexPath {
           player.stopCurrentPlayingCell()
        }
        /// 如果没有播放，则点击进详情页会自动播放
        if !(player.currentPlayerManager.isPlaying ?? true) {
           player.playTheIndexPath(indexPath, scrollToTop: false)
        }
        //self.player.playTheIndexPath(indexPath, scrollToTop: false)
    }


}
// MARK: -
extension MainViewController: UITableViewDelegate {


    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        Configs.Dimensions.screenHeight
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        playTheVideoAtIndexPath(indexPath: indexPath)
    }

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        scrollView.zf_scrollViewDidEndDecelerating()
    }

    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        scrollView.zf_scrollViewDidEndDraggingWillDecelerate(decelerate)
    }

    func scrollViewDidScrollToTop(_ scrollView: UIScrollView) {
        scrollView.zf_scrollViewDidScrollToTop()
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        scrollView.zf_scrollViewDidScroll()
    }

    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        scrollView.zf_scrollViewWillBeginDragging()
    }

}

// MARK: -
extension MainViewController: UITableViewDataSource,ZFTableViewCellDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        5
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SmallVideoCell", for: indexPath) as! SmallVideoCell
        cell.setDelegate(delegate: self, indexPath: indexPath)
        cell.backgroundColor = UIColor.init(red: CGFloat((arc4random()%256))/256.0, green: CGFloat((arc4random()%256))/256.0, blue: CGFloat((arc4random()%256))/256.0, alpha: 1)
        return cell
    }
}

extension MainViewController {

    /// 播放视频
    func playTheVideoAtIndexPath(indexPath: IndexPath,scrollToTop: Bool) {
        self.player.playTheIndexPath(indexPath, scrollToTop: scrollToTop)

    }
}
